package com.tianji.jd.data.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;


/**
 * Description: 数据源的配置
 *
 * @author chenjia
 * @version 1.0
 * @date 2024/11/12 10:09
 */
@Configuration
public class DynamicDataSourceConfig {

    @Bean(name = "masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "master1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.master1")
    public DataSource master1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicRoutingDataSource dynamicRoutingDataSource(
            @Qualifier("masterDataSource") DataSource masterDataSource,
            @Qualifier("master1DataSource") DataSource master1DataSource) {
        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
        dynamicRoutingDataSource.addDataSource("master", masterDataSource);
        dynamicRoutingDataSource.addDataSource("master1", master1DataSource);
        // 设置默认数据源
        dynamicRoutingDataSource.setPrimary("master");
        return dynamicRoutingDataSource;
    }
}
